﻿using Sandbox.Game.Gui;
using Sandbox.ModAPI;
using VRageMath;

namespace Vicizlat.MultifloorCargoElevator
{
    public partial class MultifloorCargoElevator
    {
        public IMyPistonTop ElevatorCabin;
        private Vector3D CabinPosition;
        private bool CabinReady;
        private bool ResetToBase = true;
        private bool TryAddNewTop;

        private void CheckAndGetTopPart()
        {
            if (Elevator_block.Top != null && (ElevatorCabin == null || ElevatorCabin.Closed))
            {
                ElevatorCabin = Elevator_block.Top as IMyPistonTop;
                ElevatorCabin.CubeGrid.PositionComp.OnPositionChanged += OnPositionChanged;
            }
            if (Elevator_block.Top == null || Elevator_block.Top.Closed)
            {
                if (ResetToBase)
                {
                    TryAddNewTop = false;
                    Elevator_block.Enabled = true;
                    Elevator_block.MinLimit = 0;
                    Elevator_block.Retract();
                    ResetToBase = false;
                }
                if (Elevator_block.CurrentPosition == 0)
                {
                    Elevator_block.MaxLimit = 2.5f;
                    Elevator_block.Extend();
                    TryAddNewTop = true;
                }
                if (TryAddNewTop) TerminalActionExtensions.ApplyAction(Elevator_block, "Add Top Part");
                CabinReady = false;
            }
            else
            {
                ResetToBase = true;
                if (TryAddNewTop)
                {
                    SendToFloor(1);
                    TryAddNewTop = false;
                }
                CabinReady = true;
            }
            Elevator_block.RefreshCustomInfo();
        }
    }
}